package com.cp.elasticsearch.controller;

import com.cp.elasticsearch.entity.es.EsTBlog;
import com.cp.elasticsearch.mapper.es.EsTBlogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
public class EsTBlogController {

    @Autowired
    private EsTBlogMapper esTBlogMapper;



    /**
     * 增
     *
     * @param esTBlog
     * @return
     */
    @PostMapping("/es/add")
    public ResponseEntity add(EsTBlog esTBlog) {
        esTBlogMapper.save(esTBlog);
        return ResponseEntity.ok().body(esTBlog);
    }

    /**
     * 查
     *
     * @return
     */
    @GetMapping("/es/all")
    public ResponseEntity getAll() {

        Iterable<EsTBlog> all = esTBlogMapper.findAll();
        List<EsTBlog> list = new ArrayList<>();
        all.forEach(list::add);
        return ResponseEntity.ok().body(list);
    }

    /**
     * 查
     *
     * @param id
     * @return
     */
    @GetMapping("/es/get/{id}")
    public ResponseEntity getById(@PathVariable Integer id) {
        Optional<EsTBlog> estBlog = esTBlogMapper.findById(id);
        EsTBlog esTBlog = null;
        if (estBlog.isPresent()) {
            esTBlog = estBlog.get();
        }
        return ResponseEntity.ok().body(esTBlog);

    }


    /**
     * 修改
     *
     * @param esTBlog
     * @return
     */
    @PostMapping("/es/update")
    public ResponseEntity update(@RequestBody EsTBlog esTBlog) {
        esTBlogMapper.save(esTBlog);
        return ResponseEntity.ok().body(esTBlog);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/es/delete/{id}")
    public ResponseEntity delete(@PathVariable("id") Integer id) {
        esTBlogMapper.deleteById(id);
        return ResponseEntity.ok().body(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除全部
     *
     * @return
     */
    @DeleteMapping("/es/delete/all")
    public ResponseEntity deleteAll() {
        esTBlogMapper.deleteAll();
        return ResponseEntity.ok().body(HttpStatus.NO_CONTENT);
    }


}

